import React, { useState, useEffect } from "react"
import {Button, PageHeader, Table, Tag, Form, Select, Input, DatePicker, Tooltip} from "antd";
import { ArrowLeftOutlined, SearchOutlined, CloseOutlined, ClockCircleOutlined } from "@ant-design/icons";
import moment from "moment";
import { useRequest } from '@umijs/hooks'
import { pageSetting, orderType } from "project-config"
import { formatResult } from "../../shared/libs/hooks/table-hooks"
import { get } from "server"
import { clearner } from "../../shared/libs/utils"
import {avatarPath} from "../../shared/project-config";
import "./index.less"

const { RangePicker } = DatePicker;
const { Option } = Select;

const OperationLogger = (props) => {
	const [operationTypeList, setOperationTypeList] = useState([]);
	const [adminList, setAdminList] = useState([]);

	useEffect(() => {
		get("/management/logs/operations").then(response => {
			if (response) {
				setOperationTypeList(response);
			}
		})
		get("/management/account/admin/findAdmin").then(response => {
			if (response) setAdminList(response);
		})
	}, [])

	const [form] = Form.useForm();
	//获取数据
	const getPageData = ({
		current, pageSize, sorter, filters, searchKey, operationName,
		accountId,
		beginTime,
		endTime,
	}) => {
		let result;
		if (filters && filters.result && filters.result.length === 1) {
			result = filters.result[0];
		}
		let sortKey;
		let sortType;
		if (sorter && sorter.columnKey && sorter.order) {
			sortKey = sorter.columnKey;
			sortType = orderType[sorter.order];
		}
		return get(`/management/logs/operation/${pageSize}/${current}`, clearner({
			searchKey,
			sortType,
			sortKey,
			result,
			operationName,
			accountId,
			beginTime,
			endTime,
		}))
	}


	const { tableProps, params, refresh, pagination } = useRequest(getPageData, {
		paginated: true,
		defaultPageSize: 10,
		formatResult,
	})

	const loggerColumns = [
		{
			title: "",
			dataIndex: "rowId",
			key: "rowId",
			width: 50,
			render: (_, $, index) => <b>{index + 1}</b>
		}, {
			title: "帐号",
			dataIndex: "avatar",
			key: "avatar",
			width: 150,
			render: (text, record) => (
				<div className="user-info">
					<div className="avatar">
						<img src={avatarPath(text)} />
					</div>
					<span>{record.loginName}</span>
				</div>
			)
		}, {
			title: '姓名',
			dataIndex: 'accountName',
			key: 'accountName',
			width: 100,
		}, {
			title: '手机号码',
			dataIndex: 'phoneNo',
			key: 'phoneNo',
			width: 120,
		}, {
			title: '操作内容',
			key: 'detail',
			dataIndex: 'detail',
			ellipsis: {
				showTitle: false,
			},
			render: value => (
				<Tooltip placement="topLeft" title={value}>
					{value}
				</Tooltip>
			),
		}, {
			title: '操作结果',
			key: 'result',
			width: 120,
			dataIndex: 'result',
			render: text => text === "success" ? <Tag color="#4CAF50" className="large">成功</Tag> : <Tag className="large" color="#f50">失败</Tag>,
			filters: [
				{ text: "成功", value: "success" },
				{ text: "失败", value: "failed" }
			],
		}, {
			title: '发生时间',
			key: 'createTime',
			dataIndex: 'createTime',
			sorter: true,
			width: 250,
			showSorterTooltip: false,
			sortDirections: ['ascend', 'descend', 'ascend'],
			render: (text) => text && <Tag className="large"><ClockCircleOutlined /> {text}</Tag>
		}
	]

	const onFinish = values => {
		const { durationDate, operationName, accountId } = values;
		let startDate, endDate;
		if (durationDate) {
			[startDate, endDate] = durationDate;
		}
		params[0] = {
			...params[0],
			operationName,
			accountId,
			beginTime: startDate && moment(startDate).valueOf(),
			endTime: endDate && moment(endDate).valueOf(),
		}
		refresh().finally()
	}

	const resetSearch = () => {
		form.resetFields();
		params[0] = {
			...params[0],
			operationName: '',
			accountId: '',
			beginTime: '',
			endTime: '',
		}
		refresh().finally()
	}


	const rangeConfig = {
		rules: [{ type: 'array', required: false, message: '' }],
	};

	return (
		<div className={'zr-panel'}>
			<div className={'zr-panel-header'}>
				<PageHeader backIcon={<ArrowLeftOutlined />} onBack={() => window.history.back()} title='操作日志' subTitle='' />
			</div>
			<div className={'zr-list-page-box body-bg body-border absolute'}>
				<Form
					form={form}
					name="basic"
					onFinish={onFinish}
					layout="inline"
					style={{
						margin: "20px 0px",
						justifyContent: "flex-end",
					}}
				>
					<Form.Item name="accountId" label="操作人员">
						<Select style={{ width: 200 }}
							showSearch
							allowClear
							filterOption={(input, option) =>
								option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
							}
						>
							{
								adminList.length > 0 && adminList.map(({ id, name, loginName }) => <Option key={id} value={id}>{`${name} | ${loginName}`}</Option>)
							}
						</Select>
					</Form.Item>
					<Form.Item name="operationName" label="操作类型">
						<Select showSearch allowClear
							style={{ width: 200 }}
						>
							{
								operationTypeList.length > 0 && operationTypeList.map((item, index) =>
									<Option key={index} value={item}>{item}</Option>)
							}
						</Select>
					</Form.Item>
					<Form.Item name="durationDate" label="日期段" {...rangeConfig}>
						<RangePicker showTime format="YYYY-MM-DD HH:mm:ss" />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit" style={{ marginRight: 10 }}>
							<SearchOutlined /> 查询
						</Button>
						<Button onClick={resetSearch}><CloseOutlined /> 重置</Button>
					</Form.Item>
				</Form>
				{/* <div className={cs("zr-query-box")} style={{ paddingRight: 20, }}> */}
				{/* <SearchAutoComplete style={{ marginRight: 5 }} allowClear={true} onSelect={onSearch} placeholder="请输入关键字查询" /> */}
				{/* </div> */}
				<div className="zr-table-box">
					<Table
						{...tableProps}
						pagination={{
							...pagination,
							...pageSetting
						}}
						rowKey={record => record.id}
						size='middle'
						columns={loggerColumns} />
				</div>
			</div>
		</div>
	)
}

export default OperationLogger;